package org.example.demo1.service.servicelmpl;

import org.apache.ibatis.session.SqlSession;
import org.example.demo1.DAO.NovelDao;
import org.example.demo1.Entity.Novel;
import org.example.demo1.service.Authorworkservice;
import org.example.demo1.utils.MybatisUtils;

import java.util.*;

public class Authorworkservicelmpl implements Authorworkservice {
    
    @Override
    public Map<String, Object> getAuthorStatistics(int authorId) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtils.getSqlSession();
            NovelDao novelDao = sqlSession.getMapper(NovelDao.class);
            
            // 构建查询参数 - 添加必需的分页参数
            Map<String, Object> params = new HashMap<>();
            params.put("author_id", authorId);
            params.put("offset", 0);  // 添加offset参数
            params.put("pageSize", Integer.MAX_VALUE);  // 添加pageSize参数，获取所有数据
            
            // 获取作者的所有作品
            List<Novel> authorNovels = novelDao.getNovelListPagination(params);
            
            // 计算统计数据
            int totalNovels = authorNovels.size();
            int totalWordCount = 0;
            int publishedNovels = 0;
            int draftNovels = 0;
            int totalChapters = 0;
            
            for (Novel novel : authorNovels) {
                totalWordCount += novel.getNovel_word_count();
                
                // 统计发布状态 (假设 novel_status: 0=草稿, 1=已发布, 2=下架)
                if (novel.getNovel_status() == 1) {
                    publishedNovels++;
                } else if (novel.getNovel_status() == 0) {
                    draftNovels++;
                }
                
                // 获取每本小说的章节数
                Map<String, Object> chapterParams = new HashMap<>();
                chapterParams.put("novelId", novel.getNovel_id());
                chapterParams.put("pageNum", 1);
                chapterParams.put("pageSize", Integer.MAX_VALUE);
                
                try {
                    totalChapters += novelDao.getAllChaptersByNovelId(chapterParams).size();
                } catch (Exception e) {
                    System.err.println("获取小说 " + novel.getNovel_id() + " 的章节数失败: " + e.getMessage());
                }
            }
            
            // 构建统计结果
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalNovels", totalNovels);
            statistics.put("totalWordCount", totalWordCount);
            statistics.put("publishedNovels", publishedNovels);
            statistics.put("draftNovels", draftNovels);
            statistics.put("totalChapters", totalChapters);
            
            // 计算平均字数
            int avgWordCount = totalNovels > 0 ? totalWordCount / totalNovels : 0;
            statistics.put("avgWordCount", avgWordCount);
            
            return statistics;
            
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取统计数据失败: " + e.getMessage());
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
    
    @Override
    public Map<String, Object> getAuthorNovels(int authorId, int pageNum, int pageSize, String status, String keyword) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtils.getSqlSession();
            NovelDao novelDao = sqlSession.getMapper(NovelDao.class);
            
            // 计算偏移量
            int offset = (pageNum - 1) * pageSize;
            
            // 构建查询参数
            Map<String, Object> params = new HashMap<>();
            params.put("author_id", authorId);
            params.put("offset", offset);
            params.put("pageSize", pageSize);
            
            if (status != null && !status.isEmpty()) {
                params.put("status", Integer.parseInt(status));
            }
            
            if (keyword != null && !keyword.isEmpty()) {
                params.put("novel_name", "%" + keyword + "%");
            }
            
            // 查询作品列表
            List<Novel> novels = novelDao.getNovelListPagination(params);
            
            // 为每个作品添加章节统计信息
            for (Novel novel : novels) {
                try {
                    Map<String, Object> chapterParams = new HashMap<>();
                    chapterParams.put("novelId", novel.getNovel_id());
                    chapterParams.put("pageNum", 1);
                    chapterParams.put("pageSize", Integer.MAX_VALUE);
                    
                    int chapterCount = novelDao.getAllChaptersByNovelId(chapterParams).size();
                    novel.setTotal_chapters(chapterCount);
                } catch (Exception e) {
                    novel.setTotal_chapters(0);
                    System.err.println("获取小说 " + novel.getNovel_id() + " 的章节数失败: " + e.getMessage());
                }
            }
            
            // 获取总数（用于分页）
            int total = novelDao.getNovelCount(params);
            
            Map<String, Object> result = new HashMap<>();
            result.put("total", total);
            result.put("rows", novels);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            
            return result;
            
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取作品列表失败: " + e.getMessage());
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
    
    @Override
    public Map<String, Object> createNovel(int authorId, String novelName, String introduction, 
                                          String coverUrl, List<Integer> categoryIds) {
        SqlSession sqlSession = null;
        try {
            // 参数验证
            if (novelName == null || novelName.trim().isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 400);
                result.put("msg", "作品名称不能为空");
                return result;
            }
            
            sqlSession = MybatisUtils.getSqlSession();
            NovelDao novelDao = sqlSession.getMapper(NovelDao.class);
            
            // 创建新作品对象
            Novel novel = new Novel();
            novel.setNovel_name(novelName.trim());
            novel.setAuthor_id(authorId);
            novel.setIntroduction(introduction != null ? introduction.trim() : "");
            
            // 处理封面URL：如果为空则设置默认封面，否则使用传入的URL
            if (coverUrl == null || coverUrl.trim().isEmpty()) {
                novel.setCover_url("https://mysteriouslamb.oss-cn-hangzhou.aliyuncs.com/novel/a50d6dafc1d6a8c8846145bb24b9728.png");
            } else {
                novel.setCover_url(coverUrl.trim());
            }
            
            novel.setPublish_time(new Date());
            novel.setUpdate_status(0); // 0=连载中
            novel.setNovel_status(0);  // 0=草稿
            novel.setNovel_word_count(0);
            novel.setNovel_role(0);
            
            // 插入小说
            int result = novelDao.insertNovel(novel);
            
            if (result > 0) {
                // 获取插入后的小说ID
                int novelId = novel.getNovel_id();
                
                // 插入分类关系
                if (categoryIds != null && !categoryIds.isEmpty()) {
                    for (Integer categoryId : categoryIds) {
                        try {
                            novelDao.insertNovelCategoryRelation(novelId, categoryId);
                        } catch (Exception e) {
                            System.err.println("插入分类关系失败: novelId=" + novelId + ", categoryId=" + categoryId + ", error=" + e.getMessage());
                            // 继续处理其他分类，不中断整个流程
                        }
                    }
                }
                
                sqlSession.commit();
                
                Map<String, Object> response = new HashMap<>();
                response.put("code", 200);
                response.put("msg", "作品创建成功");
                response.put("data", novel);
                return response;
                
            } else {
                sqlSession.rollback();
                Map<String, Object> response = new HashMap<>();
                response.put("code", 500);
                response.put("msg", "作品创建失败");
                return response;
            }
            
        } catch (Exception e) {
            if (sqlSession != null) {
                sqlSession.rollback();
            }
            e.printStackTrace();
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("msg", "创建作品失败: " + e.getMessage());
            return result;
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
}
